//
// Created by v on 19-6-27.
//

#ifndef JKLIBS_CMHTTPEX_H
#define JKLIBS_CMHTTPEX_H

#include <iostream>
#include <map>

// Child implement it and set to handler
class CMHttpExSetFunction
{
  public:
    virtual size_t read_callback(char *buffer, size_t size, size_t nitems,
                                 void *userdata)
    {
        return 0;
    };

    virtual size_t write_data(void *buffer, size_t size, size_t nmemb,
                              void *userp)
    {
        return 0;
    };
};

class CMHttpEx
{
  public:
    CMHttpEx();
    virtual ~CMHttpEx();

    void setDebug(bool d) { m_debug = d; }

    /**
     * Support call back of set function or save to file directly
     * If you set function, save file will never use.
     * @param f Caller create one class inherit from CMHttpExSetFunction and
     * then rewrite the function then set here.
     */
    void setFunction(CMHttpExSetFunction *f) { m_function = f; }

    void setSaveFile(const char *savefile) { m_savefile = savefile; }

    void addHeader(const char *key, const char *value)
    {
        m_header[key] = value;
    }

    void addPostData(const char *data) { m_data = data; }

    void clear()
    {
        m_header.clear();
        m_data = "";
    }

    // ctimeout - connect timeout
    // timeout - get data timeout
    // 0 - sucess
    virtual int getSecure(const char *url, const char *caPath, int ctimeout = 3,
                          int timeout = 3)                              = 0;
    virtual int get(const char *url, int ctimeout = 3, int timeout = 3) = 0;

  protected:
    bool                 m_debug;
    std::string          m_savefile;
    CMHttpExSetFunction *m_function;

    std::map<std::string, std::string> m_header;
    std::string                        m_data;
};

#endif // JKLIBS_CMHTTPEX_H
